import numpy as np
import pandas as pd
import random as rd


# n=训练集的比例，n1等于检验集的比例
def loadData(filename, n, n1):
    df = pd.read_csv(filename, header=0, sep=',', encoding="GB2312")  # , nrows=2000

    df1 = df.copy()
    df1.loc[df.gender == 'Male', 'gender'] = 1
    df1.loc[df.gender == 'Female', 'gender'] = 2
    # 1：患有糖尿病，0：不是糖尿病
    df1.loc[df.diabetesMed == 'Yes', 'diabetesMed'] = 1
    df1.loc[df.diabetesMed == 'No', 'diabetesMed'] = 0
    for i in range(df1['age'].shape[0]):
        if df1['age'][i] == '[0-10)':
            df1['age'][i] = 5
        elif df1['age'][i] == '[10-20)':
            df1['age'][i] = 15
        elif df1['age'][i] == '[20-30)':
            df1['age'][i] = 25
        elif df1['age'][i] == '[30-40)':
            df1['age'][i] = 35
        elif df1['age'][i] == '[40-50)':
            df1['age'][i] = 45
        elif df1['age'][i] == '[50-60)':
            df1['age'][i] = 55
        elif df1['age'][i] == '[60-70)':
            df1['age'][i] = 65
        elif df1['age'][i] == '[70-80)':
            df1['age'][i] = 75
        elif df1['age'][i] == '[80-90)':
            df1['age'][i] = 85
        elif df1['age'][i] == '[90-100)':
            df1['age'][i] = 95

    # 预处理数据！！！！！！！！！
    df1 = df1.convert_objects(convert_numeric=True)
    df1 = df1.fillna(method='backfill', axis=0)

    diag_1_min = df1['diag_1'].min()
    diag_1_max = df1['diag_1'].max()
    diag_1_lenth = diag_1_max - diag_1_min
    diag_2_min = df1['diag_2'].min()
    diag_2_max = df1['diag_2'].max()
    diag_2_lenth = diag_2_max - diag_2_min
    diag_3_min = df1['diag_3'].min()
    diag_3_max = df1['diag_3'].max()
    diag_3_lenth = diag_3_max - diag_3_min
    for i in range(df1['diag_1'].shape[0]):
        df1['diag_1'][i] = (df1['diag_1'][i] - diag_1_min) / diag_1_lenth
        df1['diag_2'][i] = (df1['diag_2'][i] - diag_2_min) / diag_2_lenth
        df1['diag_3'][i] = (df1['diag_3'][i] - diag_3_min) / diag_3_lenth

    mylenth = int(len(df1))
    mylenth1 = int(mylenth * n * n1)

    df_train = df1.iloc[0:int(mylenth * n), :]
    df_train.to_csv('C:/code/database/diabetic_data_train.csv', index=0)
    # df_val = df1.iloc[mylenth - mylenth1:mylenth, :]
    df_val = df1.sample(n=mylenth1, frac=None, replace=False, weights=None, random_state=24, axis=None)
    df_val.to_csv('C:/code/database/diabetic_data_val.csv', index=0)
    df_test = df1.iloc[int(mylenth * n):mylenth, :]
    df_test.to_csv('C:/code/database/diabetic_data_test.csv', index=0)
    return


def load_mycsv(filename):
    df1 = pd.read_csv(filename, header=0, sep=',', encoding="GB2312")
    dataMaztIn = []
    classLabels = []
    for i in range(df1['gender'].shape[0]):
        dataMaztIn.append(
            [1.0, df1['gender'][i], df1['age'][i], df1['time_in_hospital'][i], df1['num_lab_procedures'][i],
             df1['num_procedures'][i], df1['num_medications'][i], df1['number_outpatient'][i],
             df1['diag_1'][i],
             df1['diag_2'][i], df1['diag_3'][i], df1['number_diagnoses'][i]])
        classLabels.append(df1['diabetesMed'][i])
    return dataMaztIn, classLabels


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras import optimizers


def MyNeuralNet(x_train, y_train, x_val, y_val, x_test, y_test):
    x_train_np = np.array(x_train)
    y_train_np = np.array(y_train)
    x_val_np = np.array(x_val)
    y_val_np = np.array(y_val)
    x_test_np = np.array(x_test)
    y_test_np = np.array(y_test)

    model = Sequential()
    model.add(Dense(10, input_dim=12))
    model.add(Dense(10, activation='relu'))
    # Softmax 的输出表征了不同类别之间的相对概率
    model.add(Dense(1, activation='sigmoid'))

    # rmsprop = RMSprop(lr=1e-09, rho=0.9, epsilon=1e-08, decay=0.0)
    # 对数损失函数(binary_crossentropy)训练,这是二元分类问题会优先使用的损失函数
    # 高效的 Adam 优化器来做梯度下降,精度指标将模在型训练时收集。
    # sgd = optimizers.SGD(lr=1e-8, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])  # accuracy准确率

    hist = model.fit(x_train_np, y_train_np, epochs=5, batch_size=100, verbose=1)

    loss_val, accuracy_val = model.evaluate(x_val_np, y_val_np, batch_size=100)
    loss_test, accuracy_test = model.evaluate(x_test_np, y_test_np)

    print("检验集loss:%f检验集正确率%f" % (loss_val, accuracy_val))
    print("测试集loss:%f测试集正确率%f" % (loss_test, accuracy_test))


if __name__ == "__main__":
    # loadData("C:/code/database/diabetic_data.csv", 0.8, 0.2)
    x_train, y_train = load_mycsv("C:/code/database/diabetic_data_train.csv")
    x_val, y_val = load_mycsv("C:/code/database/diabetic_data_val.csv")
    x_test, y_test = load_mycsv("C:/code/database/diabetic_data_test.csv")
    MyNeuralNet(x_train, y_train, x_val, y_val, x_test, y_test)
